package id.net.iconpln.bb.client.view;

import id.net.iconpln.bb.client.model.BeanModelPengendalianBb;
import id.net.iconpln.bb.client.model.Stock;
import id.net.iconpln.bb.client.service.BatubaraService;
import id.net.iconpln.bb.client.service.BatubaraServiceAsync;
import id.net.iconpln.bb.client.service.MasterRPCService;
import id.net.iconpln.bb.client.service.MasterRPCServiceAsync;
import id.net.iconpln.bb.client.service.TransportRPCService;
import id.net.iconpln.bb.client.service.TransportRPCServiceAsync;
import id.net.iconpln.bb.client.util.ClientModule;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.core.FastMap;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.DateTimePropertyEditor;
import com.extjs.gxt.ui.client.widget.form.DualListField;
import com.extjs.gxt.ui.client.widget.form.DualListField.Mode;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FileUploadField;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.FormPanel.Encoding;
import com.extjs.gxt.ui.client.widget.form.FormPanel.Method;
import com.extjs.gxt.ui.client.widget.form.ListField;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.RowNumberer;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.toolbar.LabelToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class PageBbRakor_PKS extends LayoutContainer {
	private final MasterRPCServiceAsync serviceMaster = GWT.create(MasterRPCService.class);
	private final BatubaraServiceAsync rkapService = GWT.create(BatubaraService.class);
	private final TransportRPCServiceAsync service = GWT.create(TransportRPCService.class);
	private Grid grid, grid_kon;
	private FormData formData;
	private FormBinding formBindings; 
	private ToolBar toolbar = new ToolBar();
	private ToolBar toolbar2 = new ToolBar();
	private Window window;
	private Button btsimpan,btubah,btdelete, btnUpload, btnDownload;
	private ListStore storeRakor, storeRakor_kon, storeResult, storePesertaTo, storePesertaFrom;
	private DateField txttgl_kontrak;
	private Map mapParam;
	private ColumnModel cmgrid;
	private Window windowUpload;
	private TextField<String> txtnorakor, txtNoRakorNot;
	
	
	@Override
	protected void onRender(Element parent, int pos) {
	    super.onRender(parent, pos); 
	    setLayout(new FitLayout());   
	    storeResult = new ListStore(); 
	    storeRakor = new ListStore();
	    storeRakor_kon = new ListStore();
	    
	    ContentPanel cp = new ContentPanel();  	  
	    cp.setHeaderVisible(false); 
	    cp.setFrame(true);  
	    cp.setLayout(new RowLayout(Orientation.HORIZONTAL));  
	  
	    FormPanel panel = createForm();
	    formBindings = new FormBinding(panel, true); 
	    
	    
	    grid = createGrid();
	    grid.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
	    grid.getSelectionModel().addListener(Events.SelectionChange,  
	        new Listener<SelectionChangedEvent<BeanModelPengendalianBb>>() {  
	          public void handleEvent(SelectionChangedEvent<BeanModelPengendalianBb> be) {  
	            if (be.getSelection().size() > 0) {  
	              formBindings.bind((ModelData) be.getSelection().get(0));  
	            } else {  
	              formBindings.unbind();  
	            }  
	          }  
        });  	    
	    
	    grid_kon = createGridRakor_konfirm();
	    
	    
	    ContentPanel pan = new ContentPanel();
	    pan.add(grid);
	    pan.setHeaderVisible(false);
	    pan.setLayout(new FitLayout());
	    toolbar.add(new LabelToolItem("Daftar Rakor"));
	    toolbar.add(new SeparatorToolItem());
	    btnUpload = new Button("Upload");
	    btnUpload.addSelectionListener(new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				windowUpload.show();
			}
		});
	    toolbar.add(btnUpload);
	    toolbar.add(new SeparatorToolItem());
	    btnDownload = new Button("View");
	    btnDownload.addSelectionListener(new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				if (!txtnorakor.getRawValue().equals("")){
					Map mapParam = new FastMap();
		  		  	mapParam.put("no_rakor", txtnorakor.getRawValue());
		  		  
		  		  	service.getNotulenRakor("NOTULEN_RAKOR", mapParam,new AsyncCallback<List<Map>>() {
		  		  		public void onFailure(Throwable caught) {
		  		  			GWT.log(caught.getMessage(), null);
		  		  		}

		  		  		public void onSuccess(List<Map> result) {	
		  		  			Window window = new Window();
		  		  			window.setSize(600, 400);
		  		  			window.setHeading("View PDF");
		  		  			window.setUrl(GWT.getHostPageBaseURL() + "report/notulen.pdf");
		  		  			window.show();
		  		  		}
		  		  	});
				}
				  
			}
		});
	    toolbar.add(btnDownload);
	    
	    pan.setTopComponent(toolbar);
	    
	    ContentPanel pan1 = new ContentPanel();
	    pan1.setHeaderVisible(false);
	    pan1.setLayout(new FitLayout());
	    pan1.add(grid_kon);
	    toolbar2.add(new LabelToolItem("Daftar Konfirmasi Rakor "));
	    toolbar2.add(new SeparatorToolItem());
	    pan1.setTopComponent(toolbar2);
	    
	    ContentPanel panel2 = new ContentPanel();
	    panel2.setHeaderVisible(false);
	    panel2.setLayout(new RowLayout(Orientation.VERTICAL));
	    panel2.add(pan, new RowData(1, .5));
	    panel2.add(pan1, new RowData(1, .5));
	    
	    
	    cp.add(panel, new RowData(.5, 1));  
	    cp.add(panel2, new RowData(.5, 1)); 
	    add(cp, new FitData(5));  
	    
	    createWinUpload();
	  }  
	  
	  private FormPanel createForm() {  
	    FormPanel panel = new FormPanel();  
	    panel.setHeaderVisible(false);
	    
	    FieldSet fieldSet2 = new FieldSet();  
	    fieldSet2.setHeading("Undangan Rapat Koordinasi");  
	    fieldSet2.setCollapsible(false);

	    FormLayout layout2 = new FormLayout();  
	    layout2.setLabelWidth(150);  
	    fieldSet2.setLayout(layout2);
	    
	    txtnorakor = new TextField<String>();
	    txtnorakor.setName("no_rakor");
	    txtnorakor.setFieldLabel("No Rakor");
	    txtnorakor.setEnabled(false);
	    fieldSet2.add(txtnorakor, formData); 
	    
	    final TextArea txtagenda = new TextArea();
	    txtagenda.setName("agenda");
	    txtagenda.setFieldLabel("Agenda");  
	    fieldSet2.add(txtagenda, formData); 
	    
	    txttgl_kontrak = new DateField();
	    txttgl_kontrak.setPropertyEditor(new DateTimePropertyEditor("dd/MM/yyyy"));
	    txttgl_kontrak.setFieldLabel("Tanggal");
	    fieldSet2.add(txttgl_kontrak, formData);
	    
	    final TextField<String> txttempat = new TextField<String>();
	    txttempat.setName("tempat");
	    txttempat.setFieldLabel("Tempat");  
	    fieldSet2.add(txttempat, formData);  
	  
	    final TextField<String> txtalamat = new TextField<String>();
	    txtalamat.setName("alamat");
	    txtalamat.setFieldLabel("Alamat");  
	    fieldSet2.add(txtalamat, formData);
	    
	    final TextArea txtket = new TextArea();
	    txtket.setName("keterangan");
	    txtket.setFieldLabel("Keterangan");  
	    fieldSet2.add(txtket, formData);
	    
	    final DualListField lists = new DualListField<Stock>();  
	    lists.setMode(Mode.INSERT);  
	    lists.setFieldLabel("Peserta"); 
	    lists.setHideLabel(true);
	    
	    storePesertaFrom = new ListStore();  
	    serviceMaster.getMaster("PESERTA_RAKOR", new FastMap(), new AsyncCallback<List<Map>>() {
			public void onFailure(Throwable caught) {
				GWT.log(caught.getMessage(), null);
			}

			public void onSuccess(List<Map> result) {	
				storePesertaFrom.removeAll();
				storePesertaFrom.add(ClientModule.setListBaseModelFromListMap(result));
			}
		});	  
	    
	    ListField from = lists.getFromList();  
	    from.setDisplayField("nama");  	    
	    from.setStore(storePesertaFrom);  
	    final ListField to = lists.getToList();  
	    to.setDisplayField("nama");  
	    storePesertaTo = new ListStore();  
	    to.setStore(storePesertaTo);  	    
	    panel.add(fieldSet2);
	    panel.add(lists, new FormData("99%"));  
	    
	    ContentPanel p = new ContentPanel();
	    p.setHeaderVisible(false);	    
	    p.setButtonAlign(HorizontalAlignment.RIGHT);  
	    p.addButton(new Button("Submit", new SelectionListener<ButtonEvent>() {  
	      @Override  
	      public void componentSelected(ButtonEvent ce) {
	    	  	final String session = Registry.get("whoAmI");  	
	    	  	mapParam = new FastMap();
	    		mapParam.put("norakor", txtnorakor.getValue());	    		
	    		mapParam.put("agenda", txtagenda.getValue());
	    		mapParam.put("tempat", txttempat.getValue());
	    		mapParam.put("alamat", txtalamat.getValue());
	    		mapParam.put("tanggal", txttgl_kontrak.getRawValue());
	    		mapParam.put("ket", txtket.getValue());
	    		mapParam.put("createby", session);
	    		mapParam.put("app_access", "WEB");
	    		if (txtnorakor.getRawValue().equals("")){
	    			mapParam.put("crud", "CREATE");
	    		}else{
	    			mapParam.put("crud", "UPDATE");
	    		}
	    		rkapService.insertBbPengendalian("RAKOR", mapParam,new AsyncCallback<List<Map>>() {
	    			public void onFailure(Throwable caught) {
	    				GWT.log(caught.getMessage(), null);
	    			}

	    			public void onSuccess(List<Map> result) {
	    				grid.mask("load Data ....","x-mask-loading");
	    				storeRakor.removeAll();
	    				getdataRakor();
	    				grid.unmask();
	    				txttgl_kontrak.clear();
	    				
	    				if (result.size() > 0){
	    					txtnorakor.setValue(result.get(0).get("message").toString().substring(4, 15).trim());
	    					    				
		    				for (int x = 0; x < to.getStore().getCount(); x++){
		    	    			mapParam = new FastMap();
		    		    		mapParam.put("no_rakor", txtnorakor.getValue());	 
		    		    		mapParam.put("id_pltu", to.getStore().getAt(x).get("id_pltu").toString());	 
		    		    		mapParam.put("id_pemasok", to.getStore().getAt(x).get("id_pemasok").toString());
		    		    		mapParam.put("createby", session);
		    		    		mapParam.put("app_access", "WEB");
		    		    		mapParam.put("status", "");
		    		    		mapParam.put("crud", "CREATE");
		    		    		
		    		    		rkapService.insertBbPengendalian("RAKOR_PESERTA", mapParam,new AsyncCallback<List<Map>>() {
		    		    			public void onFailure(Throwable caught) {
		    		    				GWT.log(caught.getMessage(), null);
		    		    			}
	
		    		    			public void onSuccess(List<Map> result) {
		    		    			}
		    		    		});
		    				}
	    	    		}
	    			}
	    		});
	    		
	    		
		        Info.display("Notifikasi: ", "Data Berhasil Di Simpan");
	      }  
	    })); 
	    
	    p.addButton(new Button("Delete", new SelectionListener<ButtonEvent>() {  
		      @Override  
		      public void componentSelected(ButtonEvent ce) {  
		    	  	final Map mapParam = new FastMap();
		    	  	String session = Registry.get("whoAmI");
		    		mapParam.put("norakor", txtnorakor.getValue());	    		
		    		mapParam.put("agenda", txtagenda.getValue());
		    		mapParam.put("tempat", txttempat.getValue());
		    		mapParam.put("alamat", txtalamat.getValue());
		    		mapParam.put("tanggal", txttgl_kontrak.getRawValue());
		    		mapParam.put("ket", txtket.getValue());
		    		mapParam.put("createby", session);
		    		mapParam.put("app_access", "WEB");
		    		mapParam.put("crud", "DELETE");
		    	  
		    		rkapService.insertBbPengendalian("RAKOR", mapParam,new AsyncCallback<List<Map>>() {
		    			public void onFailure(Throwable caught) {
		    				GWT.log(caught.getMessage(), null);
		    			}

		    			public void onSuccess(List<Map> result) {
		    				grid.mask("load Data ....","x-mask-loading");
		    				storeRakor.removeAll();
		    				getdataRakor();
		    				grid.unmask();
		    				txttgl_kontrak.clear();
		    			}
		    		});
			    }  
		    }));  
	    
	    p.addButton(new Button("Reset", new SelectionListener<ButtonEvent>() {  
		      @Override  
		      public void componentSelected(ButtonEvent ce) {  
		    	   txtnorakor.clear();
		    	   txtagenda.clear();
		    	   txtalamat.clear();
		    	   txttempat.clear();
		    	   txttgl_kontrak.clear();
		    	   txtket.clear();
			    }  
		    }));  

	    panel.add(p);
	    return panel;  
	  }  
	  
	  private Grid createGrid() {  
	   
		final List<ColumnConfig> columns = new ArrayList<ColumnConfig>(); 
	    
		storeRakor = new ListStore();
		getdataRakor();

		RowNumberer id = new RowNumberer();  
	    id.setWidth(30);
	    
	    ColumnConfig agenda = new ColumnConfig("agenda", "Agenda", 120);
	    agenda.setAlignment(HorizontalAlignment.LEFT);
	    
	    ColumnConfig tempat = new ColumnConfig("tempat", "Tempat", 100);
	    tempat.setAlignment(HorizontalAlignment.LEFT);
	    
	    ColumnConfig alamat = new ColumnConfig("alamat", "Alamat", 250);
	    alamat.setAlignment(HorizontalAlignment.LEFT);
	    
	    ColumnConfig tgl = new ColumnConfig("tanggal", "Tanggal", 100);
	    tgl.setAlignment(HorizontalAlignment.LEFT);
	    tgl.setDateTimeFormat(DateTimeFormat.getFormat("dd/mm/yyyy"));
	    
	    ColumnConfig keterangan = new ColumnConfig("keterangan", "Keterangan", 130);
	    keterangan.setAlignment(HorizontalAlignment.LEFT);
	    
	    columns.add(agenda);
	    columns.add(tempat);
	    columns.add(alamat);
	    columns.add(tgl);
	    columns.add(keterangan);
	    
	  
	    final ColumnModel cm = new ColumnModel(columns);
	    
	    grid = new Grid(storeRakor, cm);
	    grid.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);  
	    grid.addListener(Events.CellClick, new Listener<BaseEvent>() {            
            public void handleEvent(BaseEvent ge) {
            	try{
            		String test = grid.getSelectionModel().getSelectedItem().get("tanggal");
            		String norakor = grid.getSelectionModel().getSelectedItem().get("no_rakor").toString();
            		
            		final DateTimeFormat dtFormat = DateTimeFormat.getFormat("dd/MM/yyyy");
					java.util.Date tgl = dtFormat.parse(test);
					txttgl_kontrak.setValue(tgl);
                	getdataRakor_kon(norakor);
                	
                	txtNoRakorNot.setValue(norakor);
                	
            	}catch (Exception e) {
					// TODO: handle exception
            		e.getMessage();
				}
            }
		});
	    
	    return grid;  
	  }  
	  
	  private Grid createGridRakor_konfirm() {  
		   
			final List<ColumnConfig> columns = new ArrayList<ColumnConfig>(); 
		    
			storeRakor_kon = new ListStore();
			getdataRakor_kon("");

			RowNumberer id = new RowNumberer();  
		    id.setWidth(30);
		    
		    ColumnConfig idpemasok = new ColumnConfig("no_rakor", "No Rakor", 150);
		    idpemasok.setAlignment(HorizontalAlignment.LEFT);
		    
		    ColumnConfig idpltu = new ColumnConfig("peserta", "Peserta", 120);
		    idpltu.setAlignment(HorizontalAlignment.LEFT);
		    
		    ColumnConfig tgl = new ColumnConfig("tanggal", "Tanggal", 100);
		    tgl.setAlignment(HorizontalAlignment.LEFT);
		    
		    ColumnConfig keterangan = new ColumnConfig("keterangan", "Keterangan", 130);
		    keterangan.setAlignment(HorizontalAlignment.LEFT);
		    
		    columns.add(idpemasok);
		    columns.add(idpltu);
		    columns.add(keterangan);
		    columns.add(tgl);
		   
		    cmgrid = new ColumnModel(columns);
		    
		    grid_kon = new Grid(storeRakor_kon, cmgrid);
		    
		    return grid_kon;  
		  }  
	  	  
	  private void getdataRakor() {
		  Map map = new FastMap();
		  map.put("id_pltu", "");
		  map.put("id_pemasok", "");
		  rkapService.getListPengendalianBb("RAKOR",map, new AsyncCallback<List<Map>>() {
	  			public void onFailure(Throwable caught) {
	  				GWT.log(caught.getMessage(), null);
	  			}

	  			public void onSuccess(List<Map> result) {	
	  				storeRakor.removeAll();
	  				storeRakor.add(ClientModule.setListBaseModelFromListMap(result));
	  			}
	  		});
	 }
	  
	  private void getdataRakor_kon(String norakor) {
		Map mapParam = new FastMap();
    	mapParam.put("norakor", norakor);
    	rkapService.getListPengendalianBb("RAKORKONFIRM",mapParam, new AsyncCallback<List<Map>>() {
	  			public void onFailure(Throwable caught) {
	  				GWT.log(caught.getMessage(), null);
	  			}

	  			public void onSuccess(List<Map> result) {	
	  				storeRakor_kon.removeAll();
	  				storeRakor_kon.add(ClientModule.setListBaseModelFromListMap(result));
	  				grid_kon.reconfigure(storeRakor_kon, cmgrid);
	  				GWT.log("size: " + result.size());
	  			}
	  		});

	}

	  private void createWinUpload(){
		  final FormPanel panel = new FormPanel();  
		    panel.setHeaderVisible(false);  
		    panel.setFrame(true);  
		    panel.setAction(GWT.getHostPageBaseURL() + "UploadHandler");  
		    panel.setEncoding(Encoding.MULTIPART);  
		    panel.setMethod(Method.POST);  
		    panel.setButtonAlign(HorizontalAlignment.CENTER);  
		    panel.setWidth(350);
		    
		    txtNoRakorNot = new TextField<String>();
		    txtNoRakorNot.setName("no_rakor");
		    txtNoRakorNot.setAllowBlank(false); 
		    txtNoRakorNot.setFieldLabel("No Rakor");
		    txtNoRakorNot.setEnabled(false);
		    txtNoRakorNot.setReadOnly(true);
		    panel.add(txtNoRakorNot);  
		    
		    FileUploadField file = new FileUploadField();  
		    file.setAllowBlank(false);  
		    file.setName("uploadedfile");  
		    file.setFieldLabel("File");  
		    panel.add(file);  
		    
		    
		  
		    Button btn = new Button("Submit");  
		    btn.addSelectionListener(new SelectionListener<ButtonEvent>() {  
		      @Override  
		      public void componentSelected(ButtonEvent ce) {  
		        if (!panel.isValid()) {  
		        	MessageBox.info("Action", "Failed ...................", null);  
		          return;  
		        }else{
		        	panel.setAction(GWT.getHostPageBaseURL() + "UploadHandler?jenis=rakor&no_rakor=" + txtNoRakorNot.getRawValue() );
		        	panel.submit();
		        	MessageBox.info("Action", "You file was uploaded", null);  
		        }
		        
		      }  
		    });  
		    panel.addButton(btn);  
		    
		    btn = new Button("Close");  
		    btn.addSelectionListener(new SelectionListener<ButtonEvent>() {  
		      @Override  
		      public void componentSelected(ButtonEvent ce) {  
		    	  windowUpload.hide();
		      }  
		    });  
		    panel.addButton(btn);  
		    
		    windowUpload = new Window();  
		    windowUpload.setHeading("Upload Notulen");
		    windowUpload.setWidth(400);
		    windowUpload.add(panel);
	  }
}

